import java.util.Arrays;
import java.util.Random;

import static java.util.Collections.swap;

public class test {
    public static void main(String[] args) {
        Solution s = new Solution();
        int[] arr = new int[]{5,3,8,7,1,2,6};
        s.sortArray(arr);
        System.out.println(Arrays.toString(arr));
    }
}
class Solution {
    public int[] sortArray(int[] nums) {
        randomizedQuicksort(nums, 0, nums.length-1);
        return nums;
    }
    public void randomizedQuicksort(int[] nums, int left, int right){
        if(left < right){
            int pos = randomizedPartition(nums, left, right);
            randomizedQuicksort(nums, left, pos-1);
            randomizedQuicksort(nums, pos+1, right);
        }
    }
    public int randomizedPartition(int[] nums, int left, int right){
        // 生成从left到right的随机数
        int pivot = new Random().nextInt(right - left + 1) + left;
        swap(nums, pivot, right);
        return partition(nums, left, right);
    }
    public int partition(int[] nums, int left, int right){
        int pivot = nums[right];
        int i = left-1;
        for(int j = left; j < right; j++){
            if(nums[j] < pivot){
                i++;
                swap(nums, i, j);
            }
        }
        swap(nums, i+1, right);
        return i+1;
    }
    private void swap(int[] nums, int i, int j){
        int tep = nums[i];
        nums[i] = nums[j];
        nums[j] = tep;
    }
}